<template>
  <div class="user-list">
    <!-- 面包屑 -->
    <el-row>
      <my-breadcrumb level1="人员管理" level2="人员列表"></my-breadcrumb>
    </el-row>
    <!-- 搜索 -->
    <el-row :gutter="20">
      <el-col :span="10">
        <el-input
          placeholder="请输入用户部分名称"
          v-model="query"
          @clear="getUserListData"
          @keyup.native.enter="getUserListData"
          clearable
          class="input-with-select"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="getUserListData"
          ></el-button>
        </el-input>
      </el-col>
      <el-col :span="3">
        <el-button
          type="success"
          icon="el-icon-circle-plus-outline"
          plain
          @click="dialogVisibleAdd = true"
          >添加用户</el-button
        >
      </el-col>
    </el-row>
    <!-- 分页 -->
    <el-row>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-row>
    <!-- 表格 -->
    <el-row>
      <el-table :data="tableData" style="width: 100%" size="mini" height="420">
        <el-table-column type="index" label="#" width="60"></el-table-column>
        <el-table-column prop="id" label="编号" width="100"> </el-table-column>
        <el-table-column prop="username" label="名称" width="100">
        </el-table-column>
        <el-table-column prop="departname" label="部门" width="100">
        </el-table-column>
        <el-table-column prop="duty" label="职务" width="100">
        </el-table-column>
        <el-table-column prop="safetyduty" label="安全部门" width="100">
        </el-table-column>
        <el-table-column prop="phone" label="联系方式" width="100">
        </el-table-column>
        <el-table-column prop="identitycardid" label="身份证号" width="150">
        </el-table-column>
        <el-table-column prop="sex" label="性别" width="100">
          <template slot-scope="scope">
            {{ scope.row.sex === 1 ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="id" label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-row>
              <el-tooltip effect="dark" content="编辑" placement="top">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  circle
                  plain
                  size="mini"
                  @click="handleEditUser(scope.row)"
                  :disabled="scope.row.username === 'admin'"
                ></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="删除" placement="top">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  plain
                  size="mini"
                  @click="handleDeleteUser(scope.row)"
                  :disabled="scope.row.username === 'admin'"
                ></el-button>
              </el-tooltip>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <!-- excel 导出 -->
    <!-- excel 导入 -->

    <el-row>
      <el-col :span="2">
        <my-excel-export
          filename="2019人员信息表"
          :excelTableData="excelTableData"
        >
        </my-excel-export>
      </el-col>
      <el-col :offset="1" :span="2">
        <my-excel-import
          @excelSuccess="handelExcelSuccess"
          @excelError="handelExcelError"
        ></my-excel-import>
      </el-col>
    </el-row>
    <!-- 添加用户 -->
    <com-add
      v-model="dialogVisibleAdd"
      @addUserSuccess="getUserListData"
    ></com-add>
    <!-- 编辑用户 -->
    <com-edit
      v-model="dialogVisibleEdit"
      :userInfo="currUserInfo"
      @editUserSuccess="getUserListData"
    ></com-edit>
    <!-- 分配角色 -->
    <!-- <com-auth
      :dialogVisibleAuth="dialogVisibleAuth"
      :userInfo="currUserInfo"
      @authUserClosed="dialogVisibleAuth = false"
      @authUserSuccess="getUserListData"
    ></com-auth> -->
  </div>
</template>

<script>
import MyBreadcrumb from '@/components/MyBreadcrumb'
import MyExcelExport from '@/components/MyExcelExport'
import MyExcelImport from '@/components/MyExcelImport'

import ComAdd from '@/views/users-all/users/components/ComAdd'
import ComEdit from '@/views/users-all/users/components/ComEdit'

import { convertExcelData, checkNoneDepartment } from '@/plugins/utils'

export default {
  components: {
    MyBreadcrumb,
    ComAdd,
    ComEdit,
    // ComAuth
    MyExcelExport,
    MyExcelImport
  },
  data() {
    return {
      query: '',
      tableData: [],
      total: 0,
      pageSize: 5,
      pageNum: 1,
      dialogVisibleAdd: false,
      dialogVisibleEdit: false,
      dialogVisibleAuth: false,
      currUserInfo: null
    }
  },
  created() {
    this.getUserListData()
  },
  computed: {
    // 表格导出格式数据
    excelTableData() {
      return [
        {
          title: '201901人员名单统计表',
          tHeader: [
            '用户编号',
            '姓名',
            '部门',
            '职务',
            '安全部门',
            '联系方式',
            '身份证号',
            '性别'
          ],
          keys: [
            'id',
            'username',
            'departname',
            'duty',
            'safetyduty',
            'phone',
            'identitycardid',
            'sex'
          ],
          table: JSON.parse(JSON.stringify(this.tableData)).map(item => {
            item.sex = item.sex === 1 ? '男' : '女'
            return item
          })
        }
      ]
    }
  },
  methods: {
    handleComAdd(value) {
      console.log(value, '---------------')
    },
    async getUserListData() {
      const { data } = await this.$http.get('/users', {
        params: {
          query: this.query,
          pagenum: this.pageNum,
          pagesize: this.pageSize
        }
      })
      if (data.meta.status === 200) {
        const { total, users } = data.data

        this.tableData = users
        this.total = total
      } else {
        this.$message.warning(data.meta.msg)
      }
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pageSize = val
      // 切换每页数据条目数量的时候，页码切回到 1
      this.pageNum = 1
      this.getUserListData()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.pageNum = val
      this.getUserListData()
    },

    // 删除按钮
    handleDeleteUser(userInfo) {
      this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const {
            data: { meta }
          } = await this.$http.delete('/users/' + userInfo.id)

          if (meta.status === 200) {
            this.$message.success(meta.msg)
            this.getUserListData()
          } else {
            this.$message.error(meta.msg)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 编辑用户
    handleEditUser(userInfo) {
      this.dialogVisibleEdit = true
      this.currUserInfo = JSON.parse(JSON.stringify(userInfo))
    },

    // excel 提取数据成功事件（还未提交数据）
    async handelExcelSuccess(sourceData) {
      const convertObj = {
        姓名: 'username',
        职务: 'duty',
        安全部门: 'safetyduty',
        性别: 'sex',
        联系电话: 'phone',
        身份证号: 'identitycardid',
        部门: 'departname'
      }
      const list = convertExcelData(sourceData[0].data, convertObj)

      const { data: deparmentData } = await this.$http.get('/department')

      if (deparmentData.meta.status !== 200) {
        this.$message.warning(deparmentData.meta.msg)
      }

      const noneDepartmentList = await checkNoneDepartment(
        list,
        deparmentData.data.departmentList
      )

      if (noneDepartmentList.length > 0) {
        this.$message.info(
          '以下部门尚未建立，无法导入用户数据：' + noneDepartmentList
        )
        return
      }

      const { data } = await this.$http.post('/users/all', list)

      console.log(data)

      if (data.meta.status === 201) {
        // 导入成功多少条？

        this.$message.success(data.meta.msg)
      } else {
        this.$message.warning(data.meta.msg)
      }
    },
    // excel 导入失败事件
    handelExcelError(err) {
      console.log(err)
      this.$message.error('导入失败:' + err)
    }
  }
}
</script>

<style lang="less" scoped>
.user-list {
  .el-row {
    padding: 5px 0;
  }
}
</style>
